package com.xyzwps.paimon.furina.modules.auth.service

import com.xyzwps.paimon.furina.common.AppErrorCode
import com.xyzwps.paimon.furina.common.AppException
import com.xyzwps.paimon.furina.common.DateTimeUtil
import com.xyzwps.paimon.furina.common.value.Phone
import com.xyzwps.paimon.furina.modules.auth.entity.*
import org.springframework.stereotype.Service

@Service
class UserAccountService(
    private val userAccountsRepository: UserAccountsRepository,
    private val userPasswordRepository: UserPasswordRepository
) {

    fun register(phone: Phone, encryptedPassword: String) {
        val userId = when (val result = userAccountsRepository.insert(phone)) {
            is UserAccountInsertOK -> result.userId;
            is UserAccountDuplicated -> throw AppException(AppErrorCode.PHONE_HAS_BEEN_USED, "手机号已被注册")
        }
        val userPassword = UserPassword(
            userId = userId,
            encryptedPassword = encryptedPassword,
            createTime = DateTimeUtil.currentLocalDateTime(),
            updateTime = DateTimeUtil.currentLocalDateTime()
        )
        userPasswordRepository.save(userPassword)
    }

    fun findByPhone(phone: Phone): UserAccount? = userAccountsRepository.findByPhone(phone)
}